package com.genghis.rapidcrm.web.view.freemarker;

import com.genghis.rapidcrm.web.view.RapidActionView;
import edu.jetwinner.common.EasyStringUtil;
import freemarker.core.Environment;
import freemarker.template.SimpleScalar;
import freemarker.template.Template;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xulixin
 */
@Component
public class RapidFreeMarkerSharedVariableRegister implements FreeMarkerSharedVariableRegisterAware {

    private static final Logger log = LoggerFactory.getLogger(RapidFreeMarkerSharedVariableRegister.class);

    protected Map<String, TemplateMethodModelEx> sharedVariableMap;

    @Override
    public Map<String, TemplateMethodModelEx> getSharedVariables() {
        return this.sharedVariableMap;
    }

    public RapidFreeMarkerSharedVariableRegister() {
        this.sharedVariableMap = new HashMap<>(1);
        templatePathFilter();
    }

    protected void validFilterArguments(List<?> args, int count, String filterName) throws TemplateModelException {
        if (args.size() != count) {
            throw new TemplateModelException(String.format("Wrong arguments of custom FreeMarker template function [%s]: expected %d but actual %d.",
                    filterName, count, args.size()));
        }
    }

    private void templatePathFilter() {
        String filterName = "vtemplate_path";
        this.sharedVariableMap.put(filterName, args -> {
            validFilterArguments(args, 2, filterName);
            SimpleScalar scalar = (SimpleScalar) args.get(0);
            String templateName = scalar.getAsString();
            scalar = (SimpleScalar) args.get(1);
            String moduleName = scalar.getAsString();
            if (EasyStringUtil.isNotBlank(moduleName) &&
                    !RapidActionView.DEFAULT_RAPIDCRM_MODULE.equals(moduleName)) {

                String templatePath = "../" + moduleName + "/" + templateName;
                Environment env = Environment.getCurrentEnvironment();
                try {
                    String fullIncludedTemplateName = env.toFullTemplateName(env.getCurrentTemplate().getName(),
                            templatePath);
                    Template template = env.getTemplateForImporting(fullIncludedTemplateName);
                    if (template != null) {
                        return templatePath;
                    }
                } catch (IOException e) {
                   log.debug(String.format("Template [%s] not found!", templatePath));
                }
            }
            return templateName;
        });
    }
}
